package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.HistoryServiceAdmin;
import com.dwxt.cdms.base.OperateCategory;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.constant.HealthParamCode;
import com.dwxt.cdms.constant.ReceiveDataType;
import com.dwxt.cdms.dao.*;
import com.dwxt.cdms.dao.oufu.OuFuLocDataMapper;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.oufu.OuFuData;
import com.dwxt.cdms.entity.oufu.OuFuLocData;
import com.dwxt.cdms.entity.poct.Poct;
import com.dwxt.cdms.entity.poct.Poct4;
import com.dwxt.cdms.entity.poct.Poct8;
import com.dwxt.cdms.entity.yumeng.BpData;
import com.dwxt.cdms.entity.yumeng.BtData;
import com.dwxt.cdms.entity.yumeng.HrData;
import com.dwxt.cdms.service.wx.WxMessageService;
import com.dwxt.cdms.util.DictUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class HealthService {

    private static Map<String, Object> map = new HashMap();

    @Autowired
    private HealthParameterMapper healthParameterMapper;

    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private HistoryServiceAdmin historyServiceAdmin;

    @Autowired
    private StationService stationService;

    @Autowired
    private OuFuLocDataMapper ouFuLocDataMapper;

    @Autowired
    private WxMessageService wxMessageService;
    @Autowired
    private AdminUserMapper adminUserMapper;

    public BaseResult selectHealthParameter() {
        Example example = new Example(HealthParameter.class);
        example.createCriteria().andIsNull("customerId");
        return BaseResult.ok(healthParameterMapper.selectByExample(example));
    }

    public BaseResult updateHealthParameter(HealthParameter healthParameter) {
        healthParameterMapper.updateByPrimaryKeySelective(healthParameter);
        return BaseResult.ok();
    }

    public BaseResult selectHealthRecordPage(String name, String community, Page page, String orderBy, Integer isHandle, String category, Date startTime, Date endTime, Integer paramStationId) {
        if (StringUtils.isNotBlank(orderBy)) {
            orderBy = "desc";
        }
        Integer stationId;
        Integer loginUserStation = stationService.getLoginUserStation();
        if (paramStationId == null) {
            stationId = loginUserStation;
        } else {
            stationId = paramStationId;
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Map> mapList = healthWarnRecordMapper.selectHealthRecordPage(name, community, orderBy, isHandle, stationId, category, startTime, endTime);
        PageInfo<Map> pageInfo = new PageInfo<>(mapList);
        List<Map> collect = mapList.stream().map(map1 -> {
            //map1.put("phone", map1.get("phone").toString().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            Object device_type = map1.get("device_type");
            if (device_type != null) {
                String deviceType = device_type.toString();
                String deviceDisplay = DictUtil.getDisplay("category", deviceType);
                map1.put("deviceDisplay", deviceDisplay);
            }
            return map1;
        }).collect(Collectors.toList());
        pageInfo.setList(collect);
        return BaseResult.ok(pageInfo);
    }

    public HealthParameter selectHealthParameterByCode(String code) {
        Example example = new Example(HealthParameter.class);
        example.createCriteria().andEqualTo("code", code).andIsNull("customerId");
        List<HealthParameter> healthParameters = healthParameterMapper.selectByExample(example);
        return healthParameters.size() > 0 ? healthParameters.get(0) : null;
    }

    public String judgeIsNormal(Map map) {

        StringBuilder sb = new StringBuilder();
        HealthParameter xyGy;
        HealthParameter xyDy;
        HealthParameter mb;
        //自己的健康参数
        xyGy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_GY,
                Integer.parseInt(map.get("customerId").toString()));
        if (xyGy == null) {
            xyGy = selectHealthParameterByCode(HealthParamCode.XY_GY);
        }
        xyDy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_DY,
                Integer.parseInt(map.get("customerId").toString()));
        if (xyDy == null) {
            xyDy = selectHealthParameterByCode(HealthParamCode.XY_DY);
        }
        mb = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                Integer.parseInt(map.get("customerId").toString()));
        if (mb == null) {
            mb = selectHealthParameterByCode(HealthParamCode.MB);
        }

        Integer highData = Integer.parseInt(map.get("highData").toString());
        Integer lowData = (Integer.parseInt(map.get("lowData").toString()));
        Integer heartData = (Integer.parseInt(map.get("heartData").toString()));

        if (highData < xyGy.getMin() || highData > xyGy.getMax()) {
            sb.append(xyGy.getName() + " : 异常 ");
        }
        if (lowData < xyDy.getMin() || lowData > xyDy.getMax()) {
            sb.append(xyDy.getName() + " : 异常 ");
        }
        if (heartData < mb.getMin() || heartData > mb.getMax()) {
            sb.append(mb.getName() + " : 异常 ");
        }
        if (sb.length() > 0) {
            return sb.toString();
        } else {
            return "正常";
        }

    }

    public void judgeIsNormalAndInsertRecord(Object object) {
        if (object instanceof HrData) {
            HrData data = (HrData) object;
            //设备类型
            String deviceType = "4";
            //自己的健康参数
            HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                    data.getCustomerId());
            //默认的健康参数
            HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.MB);
            //采用的健康参数
            HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
            if (data.getHr() > healthParameter.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + data.getHr() + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("HrData_" + (data.getId() == null ? "" : data.getId()));
                record.setCreateTime(DateUtils.formatTime(data.getTime()));
                record.setDefaultParameter(defaultHealthParameter.getMax());
                record.setSelfParameter(healthParameter.getMax());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }

            if (data.getHr() < healthParameter.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + data.getHr() + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("HrData_" + (data.getId() == null ? "" : data.getId()));
                record.setCreateTime(DateUtils.formatTime(data.getTime()));
                record.setDefaultParameter(defaultHealthParameter.getMin());
                record.setSelfParameter(healthParameter.getMin());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }


        } else if (object instanceof BpData) {
            BpData data = (BpData) object;
            //设备类型
            String deviceType = "4";
            HealthParameter selfXyDy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_DY,
                    data.getCustomerId());
            HealthParameter defaultXyDy = selectMapHealthParameterByCode(HealthParamCode.XY_DY);

            HealthParameter xyDy = selfXyDy == null ? defaultXyDy : selfXyDy;
            //HealthParameter xyGy = selectMapHealthParameterByCode(HealthParamCode.XY_GY);
            //HealthParameter xyDy = selectMapHealthParameterByCode(HealthParamCode.XY_DY);
            //低压
            if (data.getDiastolic() != null) {
                if (data.getDiastolic() > xyDy.getMax()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xyDy.getCategory());
                    record.setDetail(xyDy.getName() + " (" + data.getDiastolic() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXyDy.getMax());
                    record.setSelfParameter(xyDy.getMax());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }

                if (data.getDiastolic() < xyDy.getMin()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xyDy.getCategory());
                    record.setDetail(xyDy.getName() + " (" + data.getDiastolic() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXyDy.getMin());
                    record.setSelfParameter(xyDy.getMin());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }
            }

            HealthParameter selfXyGy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_GY,
                    data.getCustomerId());
            HealthParameter defaultXyGy = selectMapHealthParameterByCode(HealthParamCode.XY_GY);

            HealthParameter xyGy = selfXyGy == null ? defaultXyGy : selfXyGy;
            //高压
            if (data.getSystolic() != null) {
                if (data.getSystolic() > xyGy.getMax()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xyGy.getCategory());
                    record.setDetail(xyGy.getName() + " (" + data.getSystolic() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXyGy.getMax());
                    record.setSelfParameter(xyGy.getMax());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }

                if (data.getSystolic() < xyGy.getMin()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xyGy.getCategory());
                    record.setDetail(xyGy.getName() + " (" + data.getSystolic() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXyGy.getMin());
                    record.setSelfParameter(xyGy.getMin());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }
            }
            HealthParameter selfXy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY,
                    data.getCustomerId());
            HealthParameter defaultXy = selectMapHealthParameterByCode(HealthParamCode.XY);
            HealthParameter xy = selfXy == null ? defaultXy : selfXy;
            //血氧
            if (data.getOxygen() != null) {
                if (data.getOxygen() > xy.getMax()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xy.getCategory());
                    record.setDetail(xy.getName() + " (" + data.getOxygen() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXy.getMax());
                    record.setSelfParameter(xy.getMax());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }

                if (data.getOxygen() < xy.getMin()) {
                    HealthWarnRecord record = new HealthWarnRecord();
                    record.setCategory(xy.getCategory());
                    record.setDetail(xy.getName() + " (" + data.getOxygen() + ") 异常");
                    record.setUserId(data.getCustomerId());
                    record.setRelateId("BpData_" + (data.getId() == null ? "" : data.getId()));
                    record.setCreateTime(DateUtils.formatTime(data.getTime()));
                    record.setDefaultParameter(defaultXyGy.getMin());
                    record.setSelfParameter(xy.getMin());
                    record.setDeviceType(deviceType);
                    healthWarnRecordMapper.insertSelective(record);
                }
            }

        } else if (object instanceof BtData) {
            BtData data = (BtData) object;
            //设备类型
            String deviceType = "4";
            HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.TW,
                    data.getCustomerId());
            HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.TW);
            //采用的健康参数
            HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

            if (data.getTemp() > healthParameter.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + data.getTemp() + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("BtData_" + (data.getId() == null ? "" : data.getId()));
                record.setDefaultParameter(defaultHealthParameter.getMax());
                record.setSelfParameter(healthParameter.getMax());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }

            if (data.getTemp() < healthParameter.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + data.getTemp() + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("BtData_" + (data.getId() == null ? "" : data.getId()));
                record.setDefaultParameter(defaultHealthParameter.getMin());
                record.setSelfParameter(healthParameter.getMin());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }
        } else if (object instanceof BloodSugar) {
            BloodSugar data = (BloodSugar) object;
            //设备类型
            String deviceType = "2";
            int bloodSugar = Integer.parseInt(data.getBloodSugar());

            HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XT_KF,
                    data.getCustomerId());
            HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XT_KF);
            //采用的健康参数
            HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

            double d = strToDouble(bloodSugar);
            if (d > healthParameter.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + d + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("BloodSugar_" + (data.getId() == null ? "" : data.getId()));
                record.setDefaultParameter(defaultHealthParameter.getMax());
                record.setSelfParameter(healthParameter.getMax());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
            if (d < healthParameter.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + d + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("BloodSugar_" + (data.getId() == null ? "" : data.getId()));
                record.setDefaultParameter(defaultHealthParameter.getMin());
                record.setSelfParameter(healthParameter.getMin());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
        } else if (object instanceof Blutdruck) {
            Blutdruck data = (Blutdruck) object;
            //设备类型
            String deviceType = "1";
            //高压
            int res = Integer.parseInt(data.getHighData());

            HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_GY,
                    data.getCustomerId());
            HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XY_GY);
            //采用的健康参数
            HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

            if (res > healthParameter.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + res + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultHealthParameter.getMax());
                record.setSelfParameter(healthParameter.getMax());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
            if (res < healthParameter.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(healthParameter.getCategory());
                record.setDetail(healthParameter.getName() + " (" + res + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultHealthParameter.getMin());
                record.setSelfParameter(healthParameter.getMin());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
            //低压
            int res2 = Integer.parseInt(data.getLowData());
            HealthParameter selfXyDy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_DY,
                    data.getCustomerId());
            HealthParameter defaultXyDy = selectMapHealthParameterByCode(HealthParamCode.XY_DY);
            HealthParameter xyDy = selfXyDy == null ? defaultXyDy : selfXyDy;

            if (res2 > xyDy.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(xyDy.getCategory());
                record.setDetail(xyDy.getName() + " (" + res2 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultXyDy.getMax());
                record.setSelfParameter(xyDy.getMax());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
            if (res2 < xyDy.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(xyDy.getCategory());
                record.setDetail(xyDy.getName() + " (" + res2 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultXyDy.getMin());
                record.setSelfParameter(xyDy.getMin());
                record.setDeviceType(deviceType);
                record.setCheckTime(DateUtils.formatTime(data.getCheckTime()));
                healthWarnRecordMapper.insertSelective(record);
            }
            //心率
            int res3 = Integer.parseInt(data.getHeartData());
            //HealthParameter mb = selectMapHealthParameterByCode(HealthParamCode.MB);
            HealthParameter selfMb = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                    data.getCustomerId());
            HealthParameter defaultMb = selectMapHealthParameterByCode(HealthParamCode.MB);
            HealthParameter mb = selfMb == null ? defaultMb : selfMb;
            if (res3 > mb.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(mb.getCategory());
                record.setDetail(mb.getName() + " (" + res3 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultMb.getMax());
                record.setSelfParameter(mb.getMax());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }
            if (res3 < mb.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(mb.getCategory());
                record.setDetail(mb.getName() + " (" + res3 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("Blutdruck_" + (data.getId() == null ? "" : data.getId()));
                record.setType(data.getArrt1());
                record.setDefaultParameter(defaultMb.getMin());
                record.setSelfParameter(mb.getMin());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }
        } else if (object instanceof HeartVoice) {
            HeartVoice data = (HeartVoice) object;
            Integer id = data.getId() == null ? 0 : data.getId();

            //设备类型
            String deviceType = "3";
            //心率
            int res3 = data.getAvgHr();
            HealthParameter selfMb = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                    data.getCustomerId());
            HealthParameter defaultMb = selectMapHealthParameterByCode(HealthParamCode.MB);
            HealthParameter mb = selfMb == null ? defaultMb : selfMb;
            if (res3 > mb.getMax()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(mb.getCategory());
                record.setDetail(mb.getName() + " (" + res3 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("HeartVoice_" + id);
                record.setDefaultParameter(defaultMb.getMax());
                record.setSelfParameter(mb.getMax());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }
            if (res3 < mb.getMin()) {
                HealthWarnRecord record = new HealthWarnRecord();
                record.setCategory(mb.getCategory());
                record.setDetail(mb.getName() + " (" + res3 + ") 异常");
                record.setUserId(data.getCustomerId());
                record.setRelateId("HeartVoice_" + id);
                record.setDefaultParameter(defaultMb.getMin());
                record.setSelfParameter(mb.getMin());
                record.setDeviceType(deviceType);
                healthWarnRecordMapper.insertSelective(record);
            }
        } else if (object instanceof OuFuData) {
            OuFuData data = (OuFuData) object;
            //设备类型
            String deviceType = "5";
            //心率
            if (data.getType().equalsIgnoreCase(ReceiveDataType.HEARTBEAT)) {
                //心率
                int res3 = data.getHeartbeat();
                HealthParameter selfMb = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                        data.getCustomerId());
                HealthParameter defaultMb = selectMapHealthParameterByCode(HealthParamCode.MB);
                HealthParameter mb = selfMb == null ? defaultMb : selfMb;
                if (res3 > mb.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res3, defaultMb, mb);
                }
                if (res3 < mb.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res3, defaultMb, mb);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.BLOOD_SUGAR)) {
                //血糖
                int bloodSugar = data.getBloodSugar();
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XT_KF,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XT_KF);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

                double d = strToDouble(bloodSugar);
                if (d > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
                if (d < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.BLOOD_PRESSURE)) {
                //血压
                //高压
                int res = data.getShrink();
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_GY,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XY_GY);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                //低压
                int res2 = data.getDiastolic();
                HealthParameter selfXyDy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_DY,
                        data.getCustomerId());
                HealthParameter defaultXyDy = selectMapHealthParameterByCode(HealthParamCode.XY_DY);
                HealthParameter xyDy = selfXyDy == null ? defaultXyDy : selfXyDy;

                if (res2 > xyDy.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res2, defaultXyDy, xyDy);
                }
                if (res2 < xyDy.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res2, defaultXyDy, xyDy);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.TEMPERATURE) || data.getType().equalsIgnoreCase(ReceiveDataType.DOUBLE_TEMPERATURE)) {
                //温度
                String temperature = data.getBodyTemperature();
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.TW,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.TW);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

                double d = Double.parseDouble(temperature);
                if (d > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
                if (d < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
                //腕温
                if (data.getType().equalsIgnoreCase(ReceiveDataType.DOUBLE_TEMPERATURE)) {
                    String temp = data.getWristTemperature();
                    HealthParameter selfPara = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.WW,
                            data.getCustomerId());
                    HealthParameter defaultPara = selectMapHealthParameterByCode(HealthParamCode.WW);
                    //采用的健康参数
                    HealthParameter healthPara = selfPara == null ? defaultPara : selfPara;

                    d = Double.parseDouble(temp);
                    if (d > healthPara.getMax()) {
                        insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultPara, healthPara);
                    }
                    if (d < healthPara.getMin()) {
                        insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultPara, healthPara);
                    }
                }
            }

        } else if (object instanceof Poct8 || object instanceof Poct4) {
            Poct data;
            String deviceType;
            if (object instanceof Poct8) {
                data = (Poct8) object;
                deviceType = "7";
            } else {
                data = (Poct4) object;
                deviceType = "6";
            }
            //设备类型
            //String deviceType = "6";
            if (data.getType().equalsIgnoreCase(ReceiveDataType.BLOOD_SUGAR)) {
                //血糖
                double bloodSugar = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XT_KF,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XT_KF);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

                double d = bloodSugar;
                if (d > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
                if (d < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, d, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.URICACID)) {
                //尿酸
                double res = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.NS_UMOL,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.NS_UMOL);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;

                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.KETONE)) {
                //血酮
                double res = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XT_MMOL,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XT_MMOL);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.GLYCEROL)) {
                //甘油三酯
                double res = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.GYSZ_MMOL,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.GYSZ_MMOL);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.DDENSITY)) {
                //低密度蛋白
                double res = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.DMDDB_MMOL,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.DMDDB_MMOL);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
            } else if (data.getType().equalsIgnoreCase(ReceiveDataType.UDENSITY)) {
                //高密度蛋白
                double res = Double.parseDouble(data.getValue());
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.GMDDB_MMOL,
                        data.getCustomerId());
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.GMDDB_MMOL);
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
                if (res > healthParameter.getMax()) {
                    insetLargerData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
                if (res < healthParameter.getMin()) {
                    insertSmallData(data.getCustomerId(), data.getId(), data.getCheckTime(), deviceType, res, defaultHealthParameter, healthParameter);
                }
            }
        } else if (object instanceof LbWatchData) {
            LbWatchData data = (LbWatchData) object;
            //设备类型
            String deviceType = "12";
            //心率
            if (data.getHeartRate() != null) {
                //心率
                int res3 = data.getHeartRate();
                HealthParameter selfMb = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.MB,
                        data.getCustomerId());
                HealthParameter defaultMb = selectMapHealthParameterByCode(HealthParamCode.MB);
                HealthParameter mb = selfMb == null ? defaultMb : selfMb;
                if (res3 > mb.getMax()) {
                    insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res3, defaultMb, mb,
                            "LbWatchData_", defaultMb.getMax(), mb.getMax());
                }
                if (res3 < mb.getMin()) {
                    insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res3, defaultMb, mb,
                            "LbWatchData_", defaultMb.getMin(), mb.getMin());
                }
            }
            if (data.getSystolicPressure() != null && data.getDiastolicPressure() != null) {
                //血压
                //高压
                int res = data.getSystolicPressure();
                HealthParameter defaultHealthParameter = selectMapHealthParameterByCode(HealthParamCode.XY_GY);
                HealthParameter selfHealthParameter = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_GY,
                        data.getCustomerId());
                //采用的健康参数
                HealthParameter healthParameter = selfHealthParameter == null ? defaultHealthParameter : selfHealthParameter;
                if (res != 0 && res != 255) {

                    if (res > healthParameter.getMax()) {
                        insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res, defaultHealthParameter, healthParameter,
                                "LbWatchData_", defaultHealthParameter.getMax(), healthParameter.getMax());
                    }
                    if (res < healthParameter.getMin()) {
                        insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res, defaultHealthParameter, healthParameter,
                                "LbWatchData_", defaultHealthParameter.getMin(), healthParameter.getMin());
                    }
                }
                //低压
                int res2 = data.getDiastolicPressure();
                if (res2 != 0 && res2 != 255) {
                    HealthParameter selfXyDy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY_DY,
                            data.getCustomerId());
                    HealthParameter defaultXyDy = selectMapHealthParameterByCode(HealthParamCode.XY_DY);
                    HealthParameter xyDy = selfXyDy == null ? defaultXyDy : selfXyDy;

                    if (res2 > xyDy.getMax()) {
                        insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res2, defaultHealthParameter, xyDy,
                                "LbWatchData_", defaultHealthParameter.getMax(), xyDy.getMax());
                    }
                    if (res2 < xyDy.getMin()) {
                        insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res2, defaultHealthParameter, xyDy,
                                "LbWatchData_", defaultHealthParameter.getMin(), xyDy.getMin());
                    }
                }
            }
            if (data.getBloodOxygen() != null && data.getBloodOxygen() != 0) {
                int res = data.getBloodOxygen();
                HealthParameter selfXy = selectMapHealthParameterByCodeAndCustomerId(HealthParamCode.XY,
                        data.getCustomerId());
                HealthParameter defaultXy = selectMapHealthParameterByCode(HealthParamCode.XY);
                HealthParameter xy = selfXy == null ? defaultXy : selfXy;
                if (data.getBloodOxygen() > xy.getMax()) {
                    insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res, defaultXy, xy,
                            "LbWatchData_", defaultXy.getMax(), xy.getMax());
                }
                if (data.getBloodOxygen() < xy.getMin()) {
                    insertCommonData(data.getCustomerId(), data.getId(), data.getMeasureTime(), deviceType, res, defaultXy, xy,
                            "LbWatchData_", defaultXy.getMin(), xy.getMin());
                }
            }

        }
    }

    private void insertSmallData(Integer customerId, Object id, Date checkTime, String deviceType, Object res2, HealthParameter defaultXyDy,
                                 HealthParameter xyDy) {
        HealthWarnRecord record = new HealthWarnRecord();
        record.setCategory(xyDy.getCategory());
        record.setDetail(xyDy.getName() + " (" + res2 + ") 异常");
        record.setUserId(customerId);
        record.setRelateId("OuFuData_" + id);
        record.setDefaultParameter(defaultXyDy.getMin());
        record.setSelfParameter(xyDy.getMin());
        record.setDeviceType(deviceType);
        record.setCheckTime(checkTime);
        healthWarnRecordMapper.insertSelective(record);
    }

    private void insetLargerData(Integer customerId, Object id, Date checkTime, String deviceType, Object res, HealthParameter defaultHealthParameter,
                                 HealthParameter healthParameter) {

        HealthWarnRecord record = new HealthWarnRecord();
        record.setCategory(healthParameter.getCategory());
        record.setDetail(healthParameter.getName() + " (" + res + ") 异常");
        record.setUserId(customerId);
        record.setRelateId("OuFuData_" + id);
        record.setDefaultParameter(defaultHealthParameter.getMax());
        record.setSelfParameter(healthParameter.getMax());
        record.setDeviceType(deviceType);
        record.setCheckTime(checkTime);
        healthWarnRecordMapper.insertSelective(record);
    }

    private void insertCommonData(Integer customerId, Object id, Date checkTime, String deviceType, Object res, HealthParameter defaultHealthParameter,
                                  HealthParameter healthParameter, String category, Double defaultParameter, Double selfParameter) {

        HealthWarnRecord record = new HealthWarnRecord();
        record.setCategory(healthParameter.getCategory());
        record.setDetail(healthParameter.getName() + " (" + res + ") 异常");
        record.setUserId(customerId);
        record.setRelateId(category + id);
        record.setDefaultParameter(defaultParameter);
        record.setSelfParameter(selfParameter);
        record.setDeviceType(deviceType);
        record.setCheckTime(checkTime);
        healthWarnRecordMapper.insertSelective(record);
    }

    public HealthParameter selectMapHealthParameterByCodeAndCustomerId(String code, Integer customerId) {
        Example example = new Example(HealthParameter.class);
        example.createCriteria().andEqualTo("code", code).andEqualTo("customerId", customerId);
        List<HealthParameter> healthParameters = healthParameterMapper.selectByExample(example);
        return healthParameters.size() > 0 ? healthParameters.get(0) : null;
    }


    public HealthParameter selectMapHealthParameterByCode(String code) {
        HealthParameter healthParameter;
        Long expire = (Long) map.get(code + "_time");
        if (expire == null || expire < new Date().getTime()) {
            healthParameter = selectHealthParameterByCode(code);
            map.put(code, healthParameter);
            map.put(code + "_time", new Date().getTime() + 30 * 60 * 1000);
        } else {
            healthParameter = (HealthParameter) map.get(code);
            if (healthParameter == null) {
                healthParameter = selectHealthParameterByCode(code);
                map.put(code, healthParameter);
                map.put(code + "_time", new Date().getTime() + 30 * 60 * 1000);
            }
        }
        return healthParameter;
    }

    public BaseResult handle(Integer id, Integer isHandle) {
        HealthWarnRecord record = healthWarnRecordMapper.selectByPrimaryKey(id);
        if (record.getIsHandle() != null && !record.getIsHandle().equals(0)) {
            return BaseResult.build(StatusCode.WARN_IS_HANDLE);
        }
        record.setIsHandle(isHandle == null ? YesOrNo.YES : isHandle);
        healthWarnRecordMapper.updateByPrimaryKeySelective(record);
        String handleType = "";
        //小程序消息通知本人
        if (isHandle.equals(1)) {
            handleType = "电话处理";
        } else if (isHandle.equals(2)) {
            handleType = "上门处理";
        } else if (isHandle.equals(3)) {
            handleType = "第三方处理";
        } else if (isHandle.equals(4)) {
            handleType = "短信推送";
        } else if (isHandle.equals(5)) {
            handleType = "小程序消息推送";
        } else if (isHandle.equals(6)) {
            handleType = "预警处理流程";
        }
        Customer customer = customerMapper.selectByPrimaryKey(record.getUserId());
        String currentUserId = PartyUtil.getCurrentUserId();
        AdminUser adminUser = adminUserMapper.selectByPrimaryKey(Integer.valueOf(currentUserId));
        //小程序
        wxMessageService.sendHandleMessageToMinApp(handleType, customer, record.getDetail(), record.getCreateTime());
        // 公众号
        if (!isHandle.equals(5)) {
            wxMessageService.sendHandleMessageToGzh(customer, record.getDetail(), record.getCreateTime(), adminUser.getUsername(), handleType);
        }
        historyServiceAdmin.generate("将预警改为已处理:" + record.getId(), OperateCategory.UPDATE);
        return BaseResult.ok();
    }

    /**
     * 报警信息展示
     *
     * @param type
     * @return
     */
    public HashMap<String, Integer> selectHealthCount(Integer type) {
        Integer stationId = stationService.getLoginUserStation();
        HashMap<String, Integer> map = new HashMap<>();
        if (type == 1) {
            map.put("总报警数", healthWarnRecordMapper.selectAllCount(stationId));
        } else if (type == 2) {
            //今日报警
            map.put("今日报警", healthWarnRecordMapper.selectTodayCount(stationId));
        } else if (type == 3) {
            //本月报警
            map.put("本月报警", healthWarnRecordMapper.selectCurrentMonthCount(stationId));
        } else if (type == 4) {
            //已处理
            map.put("已处理数量", healthWarnRecordMapper.selectFinishCount(stationId));
        }
        return map;
    }

    public BaseResult selectCount(Integer queryStationId) {
        Integer stationId = stationService.getLoginUserStation();
        HashMap<Object, Object> map = new HashMap<>();
        for (int i = 1; i < 5; i++) {
            map.putAll(this.selectHealthCount(i));
        }
        CustomerExample example = new CustomerExample();
        Example equipmentExample = new Example(Equipment.class);
        if (stationId == null) {//admin
            example.createCriteria().andStationIdEqualTo(queryStationId);
            equipmentExample.createCriteria().andEqualTo("stationId", queryStationId);
        } else {//区域
            example.createCriteria().andStationIdEqualTo(stationId);
            equipmentExample.createCriteria().andEqualTo("stationId", stationId);
        }
        map.put("用户总数", customerMapper.countByExample(example));
        map.put("设备总数", equipmentMapper.selectCountByExample(equipmentExample));
        map.put("在线设备数", 0);
        map.put("离线设备数", 0);
        return BaseResult.ok(map);
    }

    public BaseResult insertOrUpdate(HealthParameter[] healthParameterList) {
        for (HealthParameter healthParameter : healthParameterList) {
            if (healthParameter.getId() == null) {
                healthParameterMapper.insertSelective(healthParameter);
            } else {
                healthParameterMapper.updateByPrimaryKeySelective(healthParameter);
            }
        }
        return BaseResult.ok();
    }

    public BaseResult selectCustomerHealthParameter(String customerId) {
        Example example = new Example(HealthParameter.class);
        example.createCriteria().andEqualTo("customerId", customerId);
        List<HealthParameter> healthParameters = healthParameterMapper.selectByExample(example);

        example.clear();
        example.createCriteria().andIsNull("customerId");
        List<HealthParameter> healthParameterList = healthParameterMapper.selectByExample(example);

        if (healthParameters.size() == 0) {
            List<HealthParameter> collect = healthParameterList.stream().map(healthParameter -> {
                healthParameter.setId(null);
                healthParameter.setCustomerId(Integer.parseInt(customerId));
                healthParameter.setCreateTime(null);
                healthParameter.setUpdateTime(null);
                return healthParameter;
            }).collect(Collectors.toList());
            return BaseResult.ok(collect);
        }
        //检查是否有漏掉的新加的参数
        checkAndCompensate(healthParameters, healthParameterList, customerId);
        return BaseResult.ok(healthParameters);
    }

    private void checkAndCompensate(List<HealthParameter> healthParameters, List<HealthParameter> healthParameterList
            , String customerId) {
        List<String> collect = healthParameters.stream().map(HealthParameter::getCode).collect(Collectors.toList());
        for (int i = 0; i < healthParameterList.size(); i++) {
            HealthParameter healthParameter = healthParameterList.get(i);
            if (!collect.contains(healthParameter.getCode())) {
                healthParameter.setId(null);
                healthParameter.setCustomerId(Integer.parseInt(customerId));
                healthParameter.setCreateTime(null);
                healthParameter.setUpdateTime(null);
                healthParameters.add(i, healthParameter);
            }
        }
    }


    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
        //Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//这个也行
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public BaseResult selectAllWarnGraphHour() {
        Integer stationId = stationService.getLoginUserStation();
        List<Integer> yArr = new ArrayList<>();
        for (int i = 2; i <= 24; i += 2) {
            Integer count = healthWarnRecordMapper.selectAllWarnGraphHour(i - 2, i, stationId);
            yArr.add(count);
        }
        return BaseResult.ok(yArr);
    }

    public BaseResult selectAllWarnGraphMonth() {
        Integer stationId = stationService.getLoginUserStation();
        List<Integer> yArr = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Integer count = healthWarnRecordMapper.selectAllWarnGraphMonth(i, stationId);
            yArr.add(count);
        }
        return BaseResult.ok(yArr);

    }

    /**
     * @方法名：strToDouble
     * @描述： 转换血糖格式为【mmol/d】
     * @作者： kjz
     * @日期： Created in 2020/10/12 17:51
     */
    public Double strToDouble(int bloodSugar) {
        double doubleBloodSugar = Double.parseDouble(bloodSugar + "");
        doubleBloodSugar = doubleBloodSugar / 18;
        //保留一位小数点，四舍五入
        String result = String.format("%.1f", doubleBloodSugar);
        return Double.valueOf(result);
    }

    public BaseResult countNotHandleWarn() {
        Integer loginUserStation = stationService.getLoginUserStation();
        Integer count = healthWarnRecordMapper.countNotHandleWarn(loginUserStation);
        return BaseResult.ok(count);
    }

    public BaseResult selectAllDataCount(Integer stationId) {
        Integer loginUserStation = stationService.getLoginUserStation();
        Map map = null;
        if (loginUserStation == null) {//admin
            map = healthWarnRecordMapper.selectAllDataCount(stationId);
        } else {//区域
            map = healthWarnRecordMapper.selectAllDataCount(loginUserStation);
        }
        return BaseResult.ok(map);
    }

    public BaseResult selectWarnByCutomerIdOrPhone(Integer customerId, String phone) {
        if (customerId == null && StringUtils.isBlank(phone)) {
            return BaseResult.build(StatusCode.PARAMETER_WRONG);
        }
        return BaseResult.ok(healthWarnRecordMapper.selectWarnByCutomerIdOrPhone(customerId, phone));
    }

    /*public BaseResult selectBackAllWarnPage(Page page, Integer queryStationId, Integer isHandle) {
        Integer stationId = stationService.getLoginUserStation();
        if (stationId == null) {//admin从参数中取区域
            stationId=queryStationId;
        }
        //区域权限，取该区域
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Map> mapList = healthWarnRecordMapper.selectAllWarnPage(null,stationId,isHandle);

        PageInfo pageInfo = new PageInfo(mapList);
        for (Map map : mapList) {
            Object category = map.get("category");
            if (isNumeric(category.toString())) {
                String warningType = DictUtil.getDisplay("warningType", category.toString());
                map.put("category", warningType);
            }
        }
        pageInfo.setList(mapList);
        return BaseResult.ok(pageInfo);

    }*/

    /*public BaseResult selectBackAllWarnPage(Page page, Integer queryStationId, Integer isHandle) {
        Integer stationId = stationService.getLoginUserStation();
        if (stationId == null) {//admin从参数中取区域
            stationId=queryStationId;
        }
        List<Map> list = new ArrayList();
        if (isHandle.equals(0)) {
            list = RedisUtil.get("notHandleList", List.class);
        } else {
            list = RedisUtil.get("handleList", List.class);
        }
        if (list != null) {
            Integer finalStationId = stationId;
            if (stationId != null) {
                list = list.stream().filter(map1 -> {
                    return finalStationId.equals(Integer.valueOf(map1.get("stationId").toString()));
                }).collect(Collectors.toList());
            }
            //创建Page类
            com.github.pagehelper.Page<Object> page1 = new com.github.pagehelper.Page<>(page.getPageNum(),page.getPageSize());
            //为Page类中的total属性赋值
            int total = list.size();
            page1.setTotal(total);
            //计算当前需要显示的数据下标起始值
            int startIndex = (page.getPageNum() - 1) * page.getPageSize();
            int endIndex = Math.min(startIndex + page.getPageSize(),total);
            //从链表中截取需要显示的子链表，并加入到Page
            page1.addAll(list.subList(startIndex,endIndex));
            //以Page创建PageInfo
            PageInfo pageInfo = new PageInfo<>(page1);
            return BaseResult.ok(pageInfo);
        }
        return BaseResult.ok();
    }
*/

    public BaseResult selectBackAllWarnPage(Page page, Integer queryStationId, Integer isHandle) {
        Integer stationId = stationService.getLoginUserStation();
        if (stationId == null) {//admin从参数中取区域
            stationId = queryStationId;
        }
        String key = "warnPage_" + isHandle.toString() + (stationId == null ? "" : stationId.toString());
        PageInfo warnPage = RedisUtil.get("warnPage_", PageInfo.class);
        if (warnPage == null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<Map> mapList = healthWarnRecordMapper.selectAllWarnPage(null, stationId, isHandle);
            for (Map map : mapList) {
                Object category = map.get("category");
                if (isNumeric(category.toString())) {
                    String warningType = DictUtil.getDisplay("warningType", category.toString());
                    map.put("category", warningType);
                }
                if (isHandle.equals(0)) {
                    int user_id = (int) map.get("user_id");
                    // 根据id查询定位信息
                    OuFuLocData ouFuLocData = ouFuLocDataMapper.selectLocByCustomerId(user_id);
                    map.put("longitude", null);
                    map.put("latitude", null);
                    if (ouFuLocData != null) {
                        map.put("longitude", ouFuLocData.getLongitude());
                        map.put("latitude", ouFuLocData.getLatitude());
                    }
                }
            }
            PageInfo pageInfo = new PageInfo(mapList);
            RedisUtil.set(key, pageInfo, 5l);
            return BaseResult.ok(pageInfo);
        }
        return BaseResult.ok(warnPage);
    }

    public void selectAllWarn() {

        List<Map> notHandleList = healthWarnRecordMapper.selectAllWarnPage(null, null, 0);
        List<Map> handleList = healthWarnRecordMapper.selectAllWarnPage(null, null, 1);
        for (Map map : notHandleList) {
            Object category = map.get("category");
            if (isNumeric(category.toString())) {
                String warningType = DictUtil.getDisplay("warningType", category.toString());
                map.put("category", warningType);
            }

            int user_id = (int) map.get("user_id");
            // 根据id查询定位信息
            OuFuLocData ouFuLocData = ouFuLocDataMapper.selectLocByCustomerId(user_id);
            map.put("longitude", null);
            map.put("latitude", null);
            if (ouFuLocData != null) {
                map.put("longitude", ouFuLocData.getLongitude());
                map.put("latitude", ouFuLocData.getLatitude());
            }
        }
        for (Map map : handleList) {
            Object category = map.get("category");
            if (isNumeric(category.toString())) {
                String warningType = DictUtil.getDisplay("warningType", category.toString());
                map.put("category", warningType);
            }
        }
        RedisUtil.set("notHandleList", notHandleList);
        RedisUtil.set("handleList", handleList);
    }

    public BaseResult selectCountForCommunity() {
        Map map = RedisUtil.get("countForCommunity", Map.class);
        if (map == null) {
            map = healthWarnRecordMapper.selectCountForCommunity();
            RedisUtil.set("countForCommunity", map);
        }
        return BaseResult.ok(map);
    }
}
